package com.crazymakercircle.imServer.handler;

import com.crazymakercircle.cocurrent.FutureTaskScheduler;
import com.crazymakercircle.im.common.bean.msg.ProtoMsg;
import com.crazymakercircle.imServer.processer.ChatRedirectProcessor;
import com.crazymakercircle.imServer.server.ServerSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 1、判断消息是否需要处理
 * 2、取得消息，并判断类型
 * 3、耗时的业务处理
 *  3.1 使用独立的netty线程组
 *  3.2 Java线程池
 * 4、把结果写入到连接通道
 */
@Slf4j
@Service("ChatRedirectHandler")
@ChannelHandler.Sharable
public class ChatRedirectHandler extends ChannelInboundHandlerAdapter {

    @Resource
    ChatRedirectProcessor chatRedirectProcessor;

    //收到消息
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断消息实例
        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        //判断消息类型
        ProtoMsg.Message pkg = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = ((ProtoMsg.Message) msg).getType();
        if (!headType.equals(chatRedirectProcessor.type())) {
            super.channelRead(ctx, msg);
            return;
        }
        //反向导航
        ServerSession session = ctx.channel().attr(ServerSession.SESSION_KEY).get();
        //判断是否登录
        if (null == session || !session.isLogin()) {
            log.error("用户尚未登录，不能发送消息");
            return;
        }
        //异步处理IM消息转发的逻辑
        FutureTaskScheduler.add(() -> {
            boolean action = chatRedirectProcessor.action(session, pkg);
            if (!action) {
                // 没有转发成功的话 给消息发送者回个消息
                //ctx.channel().writeAndFlush()
            }
        });
    }

}
